package com.example.emoji.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.style.DynamicDrawableSpan;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatMultiAutoCompleteTextView;

import com.example.emoji.R;
import com.example.emoji.handler.EmojiconHandler;

public class EmojiconMultiAutoCompleteTextView extends AppCompatMultiAutoCompleteTextView {
    private int mEmojiconSize;
    private int mEmojiconAlignment;
    private int mEmojiconTextSize;
    private boolean mUseSystemDefault = false;
    public EmojiconMultiAutoCompleteTextView(@NonNull Context context) {
        super(context);
        mEmojiconSize = (int) getTextSize();
        mEmojiconTextSize = (int) getTextSize();
    }
    public EmojiconMultiAutoCompleteTextView(Context context, AttributeSet attributeSet){
        super(context, attributeSet);
        init(attributeSet);
    }
    public EmojiconMultiAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attributeSet){
        TypedArray a = getContext().obtainStyledAttributes(attributeSet, R.styleable.Emojicon);
        mEmojiconSize = (int)a.getDimension(R.styleable.Emojicon_emojiconSize,getTextSize());
        mEmojiconAlignment = a.getInt(R.styleable.Emojicon_emojiconAlignment, DynamicDrawableSpan.ALIGN_BASELINE);
        mUseSystemDefault =  a.getBoolean(R.styleable.Emojicon_emojiconUseSystemDefault,false);
        a.recycle();
        mEmojiconTextSize  = (int)getTextSize();
        setText(getText());
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        updateText();
    }

    /**
     * Set the size of emojicon in pixels.
     */
    public void setEmojiconSize(int pixels) {
        mEmojiconSize = pixels;

        updateText();
    }

    private void updateText() {
        EmojiconHandler.addEmojis(getContext(), getText(), mEmojiconSize, mEmojiconAlignment, mEmojiconTextSize, mUseSystemDefault);
    }
    public void setUseSystemDefault(boolean useSystemDefault) {
        mUseSystemDefault = useSystemDefault;
    }
}
